package com.lechi.web.job;

import com.lechi.web.common.utils.spring.SpringUtils;
import com.lechi.web.constants.Constants;
import com.lechi.web.service.IIotMonitorDataService;
import com.lechi.web.system.domain.IotMonitorDataBo;
import com.lechi.web.system.domain.IotScheduleJobBo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 定时任务处理（允许并发执行）
 *
 * @author yg
 */
@Slf4j
public class DataCheckJobExecution extends AbstractQuartzJob {

    @Override
    protected void doExecute(JobExecutionContext context, IotScheduleJobBo job) {
        IotMonitorDataBo iotMonitorDataBo = new IotMonitorDataBo();
        iotMonitorDataBo.setDeviceId(job.getDeviceId());
        // 获取当前的日期和时间
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime beginDay = now.minusDays(1).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime endDay = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime beginHour = now.minusHours(1).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime endHour = now.withMinute(0).withSecond(0).withNano(0);
        LocalDateTime beginTime = Constants.DAY.equals(job.getCheckType()) ? beginDay : beginHour;
        LocalDateTime endTime = Constants.DAY.equals(job.getCheckType()) ? endDay : endHour;
        iotMonitorDataBo.setParams(Map.of("beginTime", beginTime.toString(), "endTime", endTime.toString()));
        iotMonitorDataBo.setTableName(Constants.MONITOR_DATA_TABLE + job.getDeviceId());
        List<LocalDateTime> monitorDataBoList = SpringUtils.getBean(IIotMonitorDataService.class).selectLostIotMonitorDataList(iotMonitorDataBo);
        long intervalNum = Duration.between(beginTime, endTime).toMinutes() / job.getIntervalTime();
        for (int i = 0; i < intervalNum; i++) {
            LocalDateTime currentTime = beginTime.plusMinutes((long) job.getIntervalTime() * i);
            boolean contains = monitorDataBoList.contains(currentTime);
            log.error("数据检查时间点：{}-{}， 检查起始时间：{}", currentTime, contains ? "数据存在" : "数据缺失", iotMonitorDataBo.getParams());
            if (!contains) {
                job.setRemark(job.getRemark() + "，" + currentTime.toLocalTime() + "：" + false);
                job.setJobName(currentTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm00")));
                sendCmd(job);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("线程休眠InterruptedException异常", e);
            }
        }
    }
}
